package system.util.message;

/**
 * Response of a requestMessage, implements a system of future.
 * If an agent try to read the content of the response message
 * whereas it is not yet available, the agent will have to wait.
 * @see system.util.message.RequestMessage
 */
public class ResponseMessage extends Message {

	private static final long serialVersionUID = -5878852493895012304L;

	/**
	 * Id of the RequestMessage which has created the response.
	 */
	private int requestMessageId;
	
	private final Object synchro = new Object();
	
	public ResponseMessage(RequestMessage m) {
		super(m.getSenderName(), (String[])null);
		this.requestMessageId = m.getId();
	}
	
	public int getRequestMessageId(){
		return requestMessageId;
	}

	@Override
	public String[] getMessage() {
		waitForMessage();
		return super.getMessage();
	}
	
	public void waitForMessage() {
		synchronized (synchro) {
			if (super.getMessage() == null) {
				try {
					synchro.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public void setMessage(String[] message) {
		synchronized (synchro) {
			super.setMessage(message);
			synchro.notifyAll();
		}
	}
	
	public void setMessage(String message) {
		this.setMessage(message.split(Message.SEPARATOR));
	}
}
